<template>
  <div class="maintenance-container">
    <!-- 头部按钮 -->
    <div class="maintenance-top-box">
      <div
        class="top-butten-box"
        @click="onOpenWorkOrderManage()"
        v-has="'maintenanceCenter:workOrderManage'"
      >
        <div class="maintenance-top-circular top-butten-color-work">
          <i class="iconfont iconweixiugongdan icon-color "></i>
        </div>
        <div class="top-text">工单管理</div>
      </div>
      <div
        class="top-butten-box"
        @click="onOpenAlarmNotification()"
        v-has="'maintenanceCenter:alarmNotice'"
      >
        <div class="maintenance-top-circular top-butten-color-police">
          <i class="iconfont iconyubaojingjilu icon-color "></i>
        </div>
        <div class="top-text">报警通知</div>
      </div>
      <div
        class="top-butten-box"
        @click="onOpenMaintenanceNotice()"
        v-has="'maintenanceCenter:maintenanceNotice'"
      >
        <div class="maintenance-top-circular top-butten-color-protect">
          <i class="iconfont iconbaoyangtongzhi icon-color "></i>
        </div>
        <div class="top-text">保养通知</div>
      </div>
      <div
        class="top-butten-box"
        @click="onOpenAddWorkOrder()"
        v-has="'maintenanceCenter:addWorkOrder'"
      >
        <div class="maintenance-top-circular top-butten-color-add">
          <i class="iconfont icongongdanshangbao icon-color "></i>
        </div>
        <div class="top-text">创建工单</div>
      </div>
    </div>
    <!-- 工程师工作台 -->
    <div
      class="maintenance-engineer-box"
      v-has="'maintenanceCenter:engineerPlatform'"
    >
      <div class="engineer-top-box">
        <div class="engineer-top-box-left">
          <div class="engineer-icon-box">
            <i class="iconfont icongongchengshi"></i>
          </div>
          <span class="top-text-left">工程师工作台</span>
        </div>
        <div
          class="top-text-right"
          @click="onOpenStayWorkOrder('allWorkOrder','5')"
        >全部工单</div>
      </div>
      <div class="engineer-single-box">
        <div class="engineer-single-stay-box">
          <div @click="onOpenStayWorkOrder('stayWorkOrder','2')">
            <p class="engineer-single-value">{{engineerArr.send}}</p>
            <p class="engineer-single-text">待接单</p>
          </div>
          <div @click="onOpenStayWorkOrder('disposeWorkOrder','3')">
            <p class="engineer-single-value">{{engineerArr.accept}}</p>
            <p class="engineer-single-text">待处理</p>
          </div>
        </div>
        <div class="engineer-progress-box">
          <div>
            <div
              class="engineer-progress-value-text"
              @click="onOpenStayWorkOrder('completeWorkOrder','4')"
            >{{engineerArr.success}}<span class="engineer-single-text">/{{engineerArr.all}}</span></div>
          </div>
          <van-progress
            :percentage="percentage"
            pivot-text=""
            stroke-width="6"
            pivot-color="#7232dd"
            color="#65E87B"
            class="engineer-progress"
          />
          <p class="engineer-progress-text">已完成工单</p>
        </div>
      </div>
    </div>

    <!-- 设备报警 -->
    <div
      class="maintenance-device-box"
      v-has="'maintenanceCenter:deviceAlarm'"
    >
      <div class="div-top-name">设备报警</div>
      <div class="swipe-div">
        <van-swipe
          class="my-swipe"
          :autoplay="3000"
          indicator-color="#3378FF"
        >
          <van-swipe-item
            v-for="(alar,index) in AlarmNoticeList"
            :key="index"
          >
            <div
              class="device-report-box"
              @click="onJumpPage(alar.id)"
            >
              <div class="device-report-icon-box">
                <i class="iconfont iconyubaojing device-icon-color"></i>
              </div>
              <div class="device-report-right-box">
                <p class="device-report-right-name">{{alar.deviceName}}</p>
                <div class="device-report-right-fault">
                  <p class="device-report-right-fault-text">故障名称</p>
                  <p class="device-report-right-fault-text">故障代码</p>
                </div>
                <div class="device-report-right-fault">
                  <p class="device-report-right-in-text">{{alar.errorName}}</p>
                  <p class="device-report-right-in-text">{{alar.errorCode}}</p>
                </div>
                <div class="device-report-right-fault">
                  <p class="device-report-right-onelevel-text">{{ detailLevelList[alar.grade - 1] }}</p>
                  <p class="device-report-right-bootem-text">{{parseTime(alar.time)}}</p>
                </div>
              </div>
            </div>
          </van-swipe-item>

        </van-swipe>
      </div>
    </div>

    <!-- 工单统计 -->
    <div
      class="maintenance-orderCount-box"
      v-has="'maintenanceCenter:workOrderStatistics'"
    >
      <div class="div-top-name echarts-text">工单统计</div>
      <div id="workOrderCount"></div>
    </div>

    <!-- 近6月通知统计 -->
    <div
      class="maintenance-monthNotice-box"
      v-has="'maintenanceCenter:sixMonthNoticeStatistics'"
    >
      <div class="div-top-name echarts-text">近6月通知统计</div>
      <div id="monthNoticeCount"></div>
    </div>

    <!-- 报警等级统计 -->
    <div
      class="maintenance-policeGrade-box"
      v-has="'maintenanceCenter:alarmLevelStatistics'"
    >
      <div class="div-top-name">报警等级统计</div>
      <div id="policeGrade"></div>
    </div>

    <!-- 维修频次TOP10 -->
    <div
      class="maintenance-topTen-box"
      v-has="'maintenanceCenter:repairFrequency'"
    >
      <div class="div-top-name">维修频次TOP10</div>
      <div class="magrin"></div>
      <div
        class="maintenance-topTen-table-box"
        v-for="(repair,index) in repairTableData"
        :key="index"
      >
        <div class="name-text">
          <p class="topTen-text-left">{{index+1}} </p>
          <p class="topTen-text-center">{{repair.name}}</p>
        </div>
        <div class="topTen-text-right">工单数：{{repair.count}}</div>
      </div>
    </div>
  </div>
</template>
<script>
import { Progress, Swipe, SwipeItem } from 'vant';
import * as echarts from 'echarts';
import { LineChart } from 'echarts/charts';
import { PieChart } from 'echarts/charts';
import { BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  DatasetComponentOption,
  TransformComponent
} from 'echarts/components';
// 标签自动布局，全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LineChart,
  PieChart,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);
import optionData from './js/chartOptions';
import {
  getAlarmNoticeList,
  getNoticeGradeCount,
  getOrderTop,
  getYearOrderCount,
  getNoticeCount,
  getOrderListByEngineerForApp
} from '@/api/maintenanceView';
export default {
  components: {
    [Progress.name]: Progress, //进度条
    [Swipe.name]: Swipe, //轮播
    [SwipeItem.name]: SwipeItem
  },
  // computed: {
  //   percentage() {
  //     return ((this.engineerArr.success / this.engineerArr.all) * 100).toFixed(0) || 0;
  //   }
  // },
  data() {
    return {
      AlarmNoticeList: [], //设备报警前五条数据
      detailLevelList: ['一级', '二级', '三级', '四级', '五级'],
      repairTableData: [], //top10
      mothArr: [], //近6月
      engineerArr: [], //工程师平台数
      percentage: 0
    };
  },
  created() {
    this.$toast.clear();
    this.onMoth();
    // this.onOrderListCunt();
    if (this.$checkBtnPermission('maintenanceCenter:deviceAlarm')) {
      this.onAlarmNoticeList(); //设备报警
    }
    if (this.$checkBtnPermission('maintenanceCenter:engineerPlatform')) {
      this.onOrderListCunt(); //工程师工作台数
    }
    if (this.$checkBtnPermission('maintenanceCenter:repairFrequency')) {
      this.onTopTen(); //top10
    }
    if (this.$checkBtnPermission('maintenanceCenter:workOrderStatistics')) {
      this.onWorkOrderCount(); //工单统计
    }
    if (this.$checkBtnPermission('maintenanceCenter:sixMonthNoticeStatistics')) {
      this.onMonthNoticeCount(); //近6月通知统计
    }
    if (this.$checkBtnPermission('maintenanceCenter:alarmLevelStatistics')) {
      this.onPoliceGrade(); //报警等级统计
    }
    // this.onTopTen();

    // this.onWorkOrderCount();
    // this.onMonthNoticeCount();
    // this.onPoliceGrade();
  },
  methods: {
    // 转化时间
    parseTime(date) {
      let time = date || '';
      const year = time.match(/^\d{4}-\d{1,2}-\d{1,2}/g);
      const second = time.match(/\d{1,2}:\d{1,2}:\d{1,2}/g);
      return year + ' ' + second;
    },
    //获取某个元素下标
    getArrayIndex(arr, obj) {
      let i = arr.length;
      while (i--) {
        if (arr[i] === obj) {
          return i;
        }
      }
      return -1;
    },
    //近6个月的
    onMoth() {
      let type = 6; //近n个月的
      let month = new Date().getMonth(); //当前月份
      let year = new Date().getFullYear(); //今年
      let dateArr = [];
      for (let i = 1; i <= type; i++) {
        let date = '';
        if (month >= i) {
          date = month - i + 1;
        } else {
          date = 12 + month - i + 1;
        }
        dateArr.push(date);
      }
      this.mothArr = dateArr.reverse();
    },
    //工程师工作台数
    onOrderListCunt() {
      getOrderListByEngineerForApp({}).then(res => {
        this.engineerArr = res.data;
        this.percentage = res.data.all === 0 ? 0 : ((res.data.success / res.data.all) * 100).toFixed(0);
      });
    },
    //设备报警
    onAlarmNoticeList() {
      getAlarmNoticeList({ page: 1, page_size: 5, type: 1 }).then(res => {
        res.data.list.map((item, index) => {
          this.AlarmNoticeList.push(item);
        });
      });
    },
    //工单统计
    onWorkOrderCount() {
      // 绘制图表
      let type = 6; //近n个月的
      let month = new Date().getMonth() + 1; //当前月份
      let year = new Date().getFullYear(); //今年
      let dateArr = [];
      for (let i = 1; i <= type; i++) {
        let date = '';
        if (month >= i) {
          if (month - i + 1 < 10) {
            date = year + '-0' + (month - i + 1);
          } else {
            date = year + '-' + (month - i + 1);
          }
        } else {
          if (12 + month - i + 1 < 10) {
            date = year - 1 + '-0' + (12 + month - i + 1);
          } else {
            date = year - 1 + '-0' + (12 + month - i + 1);
          }
        }
        dateArr.push(date);
      }
      dateArr.reverse();
      dateArr[0] = month - 6 < 10 ? year + '-0' + (month - 6) : year + '-' + (month - 6);
      let params = {
        start_time: dateArr[0] + '-01 00:00:00',
        end_time: dateArr[5] + '-01 00:00:00',
        year: year
      };
      getYearOrderCount(params).then(res => {
        let orderCountMaintain = [0, 0, 0, 0, 0, 0];
        let orderCountArra = [0, 0, 0, 0, 0, 0];
        res.data.alarmList.map((item, index) => {
          orderCountArra[this.getArrayIndex(this.mothArr, item.month)] = item.count;
        });
        res.data.maintainList.map((item1, index) => {
          orderCountMaintain[this.getArrayIndex(this.mothArr, item1.month)] = item1.count;
        });
        optionData.workOrderCountOption.series[0].data = orderCountArra;
        optionData.workOrderCountOption.series[1].data = orderCountMaintain;
        let typeChart = echarts.init(document.getElementById('workOrderCount'));
        typeChart.clear();
        typeChart.setOption(optionData.workOrderCountOption);
      });
    },
    //近6月通知统计
    onMonthNoticeCount() {
      // 绘制图表
      let type = 6; //近n个月的
      let month = new Date().getMonth() + 1; //当前月份
      let year = new Date().getFullYear(); //今年
      let dateArr = [];
      for (let i = 1; i <= type; i++) {
        let date = '';
        if (month >= i) {
          if (month - i + 1 < 10) {
            date = year + '-0' + (month - i + 1);
          } else {
            date = year + '-' + (month - i + 1);
          }
        } else {
          if (12 + month - i + 1 < 10) {
            date = year - 1 + '-0' + (12 + month - i + 1);
          } else {
            date = year - 1 + '-0' + (12 + month - i + 1);
          }
        }
        dateArr.push(date);
      }
      dateArr.reverse();
      dateArr[0] = month - 6 < 10 ? year + '-0' + (month - 6) : year + '-' + (month - 6);
      let params = {
        start_time: dateArr[0] + '-01 00:00:00',
        end_time: dateArr[5] + '-01 00:00:00',
        year: year
      };
      getNoticeCount(params).then(res => {
        let orderCountMaintain = [0, 0, 0, 0, 0, 0];
        let orderCountArra = [0, 0, 0, 0, 0, 0];
        res.data.alarmList.map((item, index) => {
          orderCountArra[this.getArrayIndex(this.mothArr, item.month)] = item.count;
        });
        res.data.maintainList.map((item1, index) => {
          orderCountMaintain[this.getArrayIndex(this.mothArr, item1.month)] = item1.count;
        });
        optionData.monthNoticeCountOption.series[1].data = orderCountArra;
        optionData.monthNoticeCountOption.series[0].data = orderCountMaintain;
        let typeChart = echarts.init(document.getElementById('monthNoticeCount'));
        typeChart.clear();
        typeChart.setOption(optionData.monthNoticeCountOption);
      });
    },
    //报警等级统计
    onPoliceGrade() {
      let tableData = [
        { value: 0, name: '一级报警' },
        { value: 0, name: '二级报警' },
        { value: 0, name: '三级报警' },
        { value: 0, name: '四级报警' },
        { value: 0, name: '五级报警' }
      ];

      let date = new Date();
      let year = date.getFullYear();
      getNoticeGradeCount({ year: year }).then(res => {
        res.data.map((item, index) => {
          tableData[item.grade - 1].value = item.count;
        });

        let myChart = echarts.init(document.getElementById('policeGrade'));
        let option = {
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '10',
            left: 'center',
            itemHeight: 10,
            itemWidth: 10
          },
          color: ['#5472C6', '#67C8FF', '#68E8E8', '#FAC858', '#EE6666'],
          series: [
            {
              top: '60',
              type: 'pie',
              radius: ['40%', '70%'],
              // width: 350,
              itemStyle: {
                borderColor: '#fff',
                borderWidth: 1
              },
              label: {
                alignTo: 'edge',
                formatter: '{name|{b}}\n{time|{d} %}',
                minMargin: 5,
                edgeDistance: 10,
                lineHeight: 25,
                rich: {
                  time: {
                    fontSize: 13,
                    color: '#606266'
                  }
                }
              },
              labelLine: {
                length: 15,
                length2: 0,
                maxSurfaceAngle: 80
              },
              labelLayout: function (params) {
                const isLeft = params.labelRect.x < myChart.getWidth() / 2;
                const points = params.labelLinePoints;
                // Update the end point.
                points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
                return {
                  labelLinePoints: points
                };
              },
              data: tableData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        };
        myChart.setOption(option);
      });
    },
    //top10
    onTopTen() {
      let date = new Date();
      let year = date.getFullYear();
      getOrderTop({ year: year, condition: 1 }).then(res => {
        this.repairTableData = res.data;
      });
    },
    //创建工单页面跳转
    onOpenAddWorkOrder() {
      this.$router.push({
        name: 'addWorkOrderManage'
      });
    },
    //工程师工单页面跳转
    //2:待接单，3:待处理，4：已完成，5：全部
    onOpenStayWorkOrder(type, val) {
      this.$router.push({
        name: type,
        query: {
          id: val
        }
      });
    },
    //工单管理页面跳转
    onOpenWorkOrderManage() {
      this.$router.push({
        name: 'workOrderManage',
        query: {
          // id: item
        }
      });
    },
    //设备报警跳详情
    onJumpPage(id) {
      this.$router.push({
        name: 'alarmNotificationDetail',
        query: {
          id: id
        }
      });
    },
    onOpenAlarmNotification() {
      this.$router.push({
        name: 'alarmNotification',
        query: {
          // id: item
        }
      });
    },
    onOpenMaintenanceNotice() {
      this.$router.push({
        name: 'maintenanceNotice',
        query: {
          // id: item
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.maintenance-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

//头部按钮样式
.maintenance-top-box {
  width: 100%;
  height: 2.72rem;
  margin-bottom: 0.266667rem;
  padding: 0.426667rem 0;
  background-color: #fff;
  display: flex;
  justify-content: space-around;
  // align-items: center;
  .top-butten-box {
    display: flex;
    flex-direction: column;
    align-items: center;

    .icon-color {
      color: #fff;
      font-size: 0.533333rem;
    }
    .top-butten-color-work {
      background: #d89aff;
    }
    .top-butten-color-police {
      background: #abdf69;
    }
    .top-butten-color-protect {
      background: #f2cf42;
    }
    .top-butten-color-add {
      background: #76a4ff;
    }
    .maintenance-top-circular {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 1.12rem;
      height: 1.12rem;
      border-radius: 0.48rem;
      // padding: 0.293333rem 0.293333rem;
      margin-bottom: 0.213333rem;
      // margin-left: 0.133333rem;
    }
    .top-text {
      color: #333333;
      font-size: 0.346667rem;
    }
  }
}

//工程师工作台
.maintenance-engineer-box {
  width: 100%;
  height: 3.413333rem;
  margin-bottom: 0.213333rem;
  padding: 0.426667rem 0.64rem;
  background-color: #fff;
  .engineer-top-box-left {
    display: flex;
  }
  .engineer-top-box {
    display: flex;
    justify-content: space-between;
  }
  .engineer-icon-box {
    width: 0.64rem;
    height: 0.64rem;
    border-radius: 0.8rem;
    background: #ebf1ff;
    color: var(--color-primary);
    font-size: 0.4rem;
    padding: 0.106667rem 0.106667rem;
  }
  .top-text-left {
    font-size: 0.373333rem;
    margin-top: 0.133333rem;
    margin-left: 0.213333rem;
  }
  .top-text-right {
    font-size: 0.373333rem;
    color: var(--color-primary);
    margin-top: 0.133333rem;
  }

  .engineer-single-box {
    margin-top: 0.466667rem;
    margin-left: 0.533333rem;
    display: flex;
  }
  .engineer-single-stay-box {
    display: flex;
    width: 35%;
    justify-content: space-between;
  }
  .engineer-single-value {
    color: var(--color-primary);
    font-size: 0.48rem;
    text-align: center;
  }
  .engineer-single-text {
    color: #999999;
    font-size: 0.32rem;
    margin-top: 0.4rem;
    text-align: center;
  }
  .engineer-progress-box {
    margin-left: 0.933333rem;
  }
  .engineer-progress {
    width: 4.266667rem;
    margin-top: 0.133333rem;
    margin-bottom: 0.16rem;
  }
  .engineer-progress-value-text {
    color: #67c23a;
    font-size: 0.426667rem;
  }
  .engineer-progress-text {
    color: #999999;
    font-size: 0.32rem;
  }
}

// 设备报警
.maintenance-device-box {
  width: 100%;
  height: 4.96rem;
  margin-bottom: 0.213333rem;
  padding: 0.426667rem 0.64rem;
  background-color: #fff;

  .device-report-box {
    margin-top: 0.426667rem;
    display: flex;
  }
  .device-report-icon-box {
    width: 1.28rem;
    height: 1.28rem;
    background: #fef0f0;
    border-radius: 0.8rem;
    margin-top: 0.666667rem;
    margin-right: 0.4rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .device-icon-color {
    color: #f56c6c;
    font-size: 0.666667rem;
  }

  .device-report-right-box {
    position: relative;
    padding-left: 0.4rem;
    padding-top: 0.133333rem;
    width: 7.04rem;
  }
  .device-report-right-box:before {
    content: '';
    position: absolute;
    top: 1px;
    left: 0;
    width: 1px;
    height: 2.693333rem;
    background-color: #f2f6fc;
  }
  .device-report-right-name {
    font-size: 0.4rem;
    margin-bottom: 0.266667rem;
  }
  .device-report-right-fault {
    display: flex;
    justify-content: space-between;
  }
  .device-report-right-fault-text {
    color: #666666;
    font-size: 0.32rem;
    margin-bottom: 0.266667rem;
  }
  .device-report-right-in-text {
    color: #666666;
    font-size: 0.346667rem;
    margin-bottom: 0.266667rem;
  }
  .device-report-right-onelevel-text {
    border: 1px solid #85aeff;
    border-radius: 0.053333rem;
    padding: 0.08rem 0.106667rem;
    color: #2454b3;
    font-size: 0.266667rem;
  }
  .device-report-right-bootem-text {
    color: #999999;
    font-size: 0.346667rem;
  }
}

//工单统计
.maintenance-orderCount-box {
  width: 100%;
  height: 7.493333rem;
  margin-bottom: 0.213333rem;
  padding-top: 0.426667rem;
  background-color: #fff;
  #workOrderCount {
    width: 100%;
    height: 100%;
  }
}
.echarts-text {
  margin-left: 0.64rem;
}

//近6月通知统计
.maintenance-monthNotice-box {
  width: 100%;
  height: 6.373333rem;
  margin-bottom: 0.213333rem;
  padding-top: 0.426667rem;
  background-color: #fff;
  #monthNoticeCount {
    width: 100%;
    height: 100%;
  }
}
//报警等级统计
.maintenance-policeGrade-box {
  width: 100%;
  height: 9.044rem;
  margin-bottom: 0.213333rem;
  padding: 0.426667rem 0.64rem;
  background-color: #fff;
  #policeGrade {
    width: 100%;
    height: 100%;
  }
}
//维修频次TOP10
.maintenance-topTen-box {
  width: 100%;
  margin-bottom: 0.213333rem;
  padding: 0.426667rem 0.64rem;
  background-color: #fff;
  .magrin {
    margin-top: 0.533333rem;
  }
  .maintenance-topTen-table-box {
    display: flex;
    border-top: 1px solid#F2F6FC;
    justify-content: space-between;
    margin-top: 0.4rem;
    padding-top: 0.4rem;
  }
  .name-text {
    display: flex;
  }
  .topTen-text-left {
    color: #cccccc;
    font-size: 0.373333rem;
  }
  .topTen-text-center {
    color: #666666;
    font-size: 0.373333rem;
    margin-left: 0.213333rem;
  }
  .topTen-text-right {
    color: #666666;
    font-size: 0.373333rem;
    flex-shrink: 0;
    margin-left: 0.026667rem;
  }
}

//tab名称样式
.div-top-name {
  position: relative;
  padding-left: 0.266667rem;
  font-size: 0.373333rem;
  color: var(--color-primary);
}
.div-top-name:before {
  content: '';
  position: absolute;
  top: 1px;
  left: 0;
  width: 0.053333rem;
  height: 0.346667rem;
  background-color: var(--color-primary);
}

//轮播
.swipe-div {
  height: 4.133333rem;
}
.my-swipe {
  height: 100%;
}
// .van-swipe-item {
//   // color: #fff;
//   // font-size: 20px;
//   // line-height: 150px;
//   // text-align: center;
//   // background-color: #fff;
//   // height: 100%;
// }
</style>